﻿#pragma once
#include <list>
#include "GObject.h"
#include <set>
#include "Collision.h"
	
class QuadNode
{
public:
	QuadNode(float x, float y, int width, int height);
	~QuadNode(void);

	void AddObject(GObject* object,int Height);
	void removeObject(GObject* object);
	int CheckRect(RECT rect);
	std::set<GObject*> getObjectList();
	void setObjectList(std::set<GObject*> newList);
	std::set<GObject*> getAllObjectList();
	QuadNode* getNode(const RECT &rect);
	std::set<GObject*> getCollidableObject(const RECT &rect);
	std::set<GObject*> getObjectInRect(const RECT &rect);
	//std::set<GObject*> popMovingObject(const RECT &rect);			// get all suitable objects, moving them out of the tree and put to this list
	bool isIntersect(RECT rect1, RECT rect2);
	bool isBelong(GObject* object);

	RECT getRect(){return _nodeRect;};
	RECT getLooseRect(){return _looseRect;};

	QuadNode** getNodeList();

	bool isDivided();

	RECT calChildRect(int childIndex);

	void free();
	void setLeaf();
	//bool inside(const RECT &rect1, const RECT &rect2);

	int countObject();


protected:
	RECT _nodeRect,_looseRect;
	int _maxHeight;

	QuadNode **_nodeList;
	std::set<GObject*> _objectList;


	bool _isDivided;

	const static int TL = 1;	//TOP LEFT
	const static int TR = 2;	//TOP RIGHT
	const static int BR = 3;	//BOTTOM RIGHT
	const static int BL = 4;	//BOTTOM LEFT
};

class QuadTree
{
protected:
	QuadNode* _root;
	Collision _coll;
public:
	QuadTree(void);
	QuadTree(int width, int height);
	~QuadTree(void);

	void add(GObject* obj);
	QuadNode* getRoot(){ return this->_root;};
	void update(std::set<GObject*> updatelist);
	std::set<GObject*> fixTree(QuadNode* currentNode, const RECT& rect);

	std::set<GObject*> checkCollision(QuadNode *currentNode, const RECT &rect); // duyệt cây,xử lý va chạm, trả về danh sách các obj cần cập nhật lại vị trí trên cây
};